package com.memoryangelapplication;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.memoryangelapplication.services.EventAlarm;

@SuppressWarnings("deprecation")
public class AlertMessageSinglePreviewTesting extends Activity implements
TextToSpeech.OnInitListener {
	String eventTimeStamp;
	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "memoryangel.db";
	private String MEM_EVENT = "table_events";
	
	//Display Variables
	String  title;  // Index(3)
	String  description;  // Index(4)
	String  reminder_date;  // Index(6)
	String 	reminder_time; // Index(7)
	String  event_count_flag; 
		
	//Handling Variables
	String  event_id; // Index(0)
	String  event_alam_time; // Index(8)
	String  event_url; // Index(11)
	String  event_package; // Index(12)
	String  event_ack_count; // Index(15)
	String  eventReminderTime; // Index(16)
	String  eventReminderNumber; // Index(17)
	String  eventWaitTime; // Index(18)
	String  eventNotifyType; // Index(19)
	
	//JSONObject eventsListObj = null;
	JSONObject eventsListObjArray = null;
	ArrayList<String> eventsListArray = new ArrayList<String>();
	int TotalEvents = 0;
	RelativeLayout lowestLayout;
	private String eventsMainArray;
	JSONArray jsonarray;
	String updateEventId;
	long nextReminderTimeStamp;
	
	EditText etEventMainId;
	TextView txtViewTitle, txtViewDescription, txtViewReminderDate, txtViewReminderTime, txtViewReminderCount;
	int CurrentPrintIndex = 0;

	ScheduledThreadPoolExecutor executor;
	//ScheduledThreadPoolExecutor executor1;
	Handler handler, main_handelr;
	SoundManager soundManager;
	//SoundManager1 soundManager1;
	TextToSpeech talker;
	String evtDes;
	MediaPlayer player;
	//=====================================
	int wait_time = 0;
	int eventwaittimePeriod = 0;
	String DateSendAct, TimeAct, Tzone;
	long TimeStampValue;
	int event_reminder_time = 0;
	int reminder_number = 0;
	int eventTTS = 1;
	int eventContPlay = 1;
	int eventSoundGap = 1000;
	
	String eventURL;
	String eventPackage;
	boolean checkMultipleActive = false;
	
	public static int counter = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Remove title bar
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    //Remove notification bar
	    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.event_values);
		
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
		
		getWindow().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
		
		KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);  
		KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE); 
		lock.disableKeyguard();

		etEventMainId  = (EditText) findViewById(R.id.eventmainid);
		txtViewTitle  = (TextView) findViewById(R.id.title);
		txtViewDescription  = (TextView) findViewById(R.id.description);
		txtViewReminderDate  = (TextView) findViewById(R.id.reminder_date);
		txtViewReminderTime  = (TextView) findViewById(R.id.reminder_time);
		txtViewReminderCount  = (TextView) findViewById(R.id.eventcounter);
		
		ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
		lowestLayout = (RelativeLayout)this.findViewById(R.id.alert_layout);
		lowestLayout.setOnTouchListener(activitySwipeDetector);
		
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			eventTimeStamp = bundle.getString("eventTimeStamp");
			String CurrentPrintIndexStr = bundle.getString("eventDisplayIDFlag");
			CurrentPrintIndex = Integer.parseInt(CurrentPrintIndexStr);
			
			mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
			Cursor fdealerrows = null;
			try {
				String query = "SELECT * FROM table_events WHERE eventTimeStamp = '" + eventTimeStamp + "' AND event_active = '0'";
				fdealerrows = mydb.rawQuery(query, null);
			} catch (Exception e) {
				Log.v("Print Exception ","1 :" + e);
			}
			if (fdealerrows != null) {
				if (fdealerrows.getCount() > 0) {
					Log.v("Total Count "," : " + fdealerrows.getCount());
					TotalEvents = fdealerrows.getCount();
					int eventIndexCounter = 0;
					while (fdealerrows.moveToNext()) {
						
						Log.v("@@@@@@@@@@@@ "," : " + eventIndexCounter);
						JSONObject eventsListObj = new JSONObject();
						try{
							eventsListObj.put("event_rf_id", eventIndexCounter);
							eventsListObj.put("title", fdealerrows.getString(3));
							eventsListObj.put("description", fdealerrows.getString(4));
							eventsListObj.put("reminder_date", fdealerrows.getString(6));
							eventsListObj.put("reminder_time", fdealerrows.getString(7));
							
							int  eventPrintCount = eventIndexCounter;
							eventPrintCount =  eventPrintCount + 1;
							eventsListObj.put("event_count_flag", eventPrintCount + "  Of  " + TotalEvents + "  Events");
							
							eventsListObj.put("event_id", fdealerrows.getString(1));
							eventsListObj.put("event_alam_time", fdealerrows.getString(8));
							eventsListObj.put("event_url", fdealerrows.getString(11));
							eventsListObj.put("event_package", fdealerrows.getString(12));
							eventsListObj.put("event_ack_count", fdealerrows.getString(15));
							eventsListObj.put("eventReminderTime", fdealerrows.getString(16));
							eventsListObj.put("eventReminderNumber", fdealerrows.getString(17));
							eventsListObj.put("eventWaitTime", fdealerrows.getString(18));
							eventsListObj.put("eventNotifyType", fdealerrows.getString(19));
							eventsListArray.add(eventsListObj.toString());
							eventIndexCounter = eventIndexCounter + 1;
						}
						catch(Exception e){
							Log.v("Print Exception ","2 :" + e);
						}
						
					}
					
					try{
						eventsListObjArray = new JSONObject();
						String EventsArray = eventsListArray.toString();
						eventsListObjArray.put("events", EventsArray);
						
					}
					catch(Exception e){
						Log.v("Print Exception ","3 :" + e);
					}
					//displayEvent();
					printFirstRecord();
				}
			}
		}
	}
	
	
	
	
	private void printFirstRecord() {
		// TODO Auto-generated method stub
		eventsMainArray = eventsListObjArray.toString();
		eventsMainArray = eventsMainArray.replace("\\", "");
		eventsMainArray = eventsMainArray.replace("\"[{", "[{");
		eventsMainArray = eventsMainArray.replace("}]\"}", "}]}");
		//CurrentPrintIndex = 0;
		Log.v("","*************************************: " + CurrentPrintIndex);
		Log.v("","" + eventsMainArray);
		Log.v("","*************************************");
		if(CurrentPrintIndex < 0){
			CurrentPrintIndex = 0;
		}
		String event_id_print = "", title_print = "" , reminder_date_print = "", reminder_time_print = "", event_count_flag_print = "";
		
		try {
			JSONObject jsonObj = new JSONObject(eventsMainArray);
			jsonarray = jsonObj.getJSONArray("events");
            for (int i = 0; i < jsonarray.length(); i++) {
            	JSONObject c = jsonarray.getJSONObject(CurrentPrintIndex);
            	event_id_print = c.getString("event_id");
            	title_print = c.getString("title");
            	evtDes = c.getString("description");
            	reminder_date_print = c.getString("reminder_date");
            	reminder_time_print = c.getString("reminder_time");
            	event_count_flag_print = c.getString("event_count_flag");
            	
            	updateEventId = c.getString("event_alam_time");
            	
            	etEventMainId.setText(event_id_print);
            	txtViewTitle.setText(title_print);
            	txtViewDescription.setText(evtDes);
            	txtViewReminderDate.setText(reminder_date_print);
            	txtViewReminderTime.setText(reminder_time_print);
            	txtViewReminderCount.setText(event_count_flag_print);
            
            	String StrEventWaitTime = c.getString("eventWaitTime");
    			eventwaittimePeriod = Integer.parseInt(StrEventWaitTime);
    			wait_time = eventwaittimePeriod * 1000;
    			//***************************************************
    			String StreventReminderTime = c.getString("eventReminderTime");
    			event_reminder_time = Integer.parseInt(StreventReminderTime);
    			//***************************************************
    			String StreventReminderNumber = c.getString("eventReminderNumber");
    			reminder_number = Integer.parseInt(StreventReminderNumber);
    		
    			//***************************************************
    			
    			if (reminder_number == 0) {
					reminder_number = 3;

				}
				// Reminder Delay
				if (event_reminder_time == 0) {
					event_reminder_time = 60;

				}
				// Display Reminder
				if (wait_time == 0) {
					// if 0 then default will be 5
					wait_time = 45 * 1000;
				}
				eventTTS = 1;
				eventContPlay = 1;
				eventSoundGap = 1000;

				if (eventSoundGap == 0) {
					eventSoundGap = 5;
				}
				
				//***************************************************
    			// Time Zone Of the Current Phone
    			Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
    			Date currentLocalTime = calendar.getTime();
    			DateFormat date = new SimpleDateFormat("Z");
    			Tzone = date.format(currentLocalTime);
    			Tzone = " " + Tzone;
    			String currentTime = getAddDateTimeStringPreCheck();
    			String[] CheckDayTime = currentTime.split(" ");
    			DateSendAct = CheckDayTime[0];
    			TimeAct = CheckDayTime[1];
    			getNativeTimeStamp(DateSendAct, TimeAct, Tzone);
    			
    			try {
    				executor = new ScheduledThreadPoolExecutor(1);
    				//executor1 = new ScheduledThreadPoolExecutor(1);

    				talker = new TextToSpeech(this, this);
    				main_handelr = new Handler();
    				
    				new CountDownTimer(wait_time, 1000) {
    					public void onTick(long millisUntilFinished) {
    						Log.e("Timmer Started", "Timmer Started");
    					}

    					// Remove Alertfrom the screen
    					// Set Next Alert
    					// Update Backend
    					public void onFinish() {
    						 if(TotalEvents > 1){
    							 Log.v(">>>>>>>>>>>>><","onFinish Multiple>");
    							 	executor.shutdown();
 									executor.shutdownNow();
 									executor.remove(soundManager);

	 								/*executor1.shutdown();
	 								executor1.shutdownNow();
	 								executor1.remove(soundManager1);*/
	 								if (talker != null) {
	 									talker.stop();
	 									talker.shutdown();
	 								}
	 								
	 						    	eventDetailsUpdate();

    								CurrentPrintIndex = CurrentPrintIndex + 1;
    								if(CurrentPrintIndex == TotalEvents){
    									//onRightToLeftSwipe();
    								}
    								if(CurrentPrintIndex > TotalEvents){
    									CurrentPrintIndex = CurrentPrintIndex - 2;
    									onRightToLeftSwipe();
    								}
    								else{
    									onRightToLeftSwipe();
    								}
    								
    					    		//printFirstRecord();
    					    		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    						    }
    						    else{
    						    	Log.v(">>>>>>>>>>>>><","onFinish Single>");
    						    	executor.shutdown();
    								executor.shutdownNow();
    								executor.remove(soundManager);

    								/*executor1.shutdown();
    								executor1.shutdownNow();
    								executor1.remove(soundManager1);*/
    								if (talker != null) {
    									talker.stop();
    									talker.shutdown();
    								}
    								
    						    	eventDetailsUpdate();
    								setNextReminder();
    								AlertMessageSinglePreviewTesting.this.finish();
    						    }
    					}

						private void onRightToLeftSwipe() {
							// TODO Auto-generated method stub
							Log.v("<<<<<<","Moving Multiple>>>>>>");
							Intent intentDirectLog = new Intent(getBaseContext(),
									AlertMessageSinglePreview.class);
							intentDirectLog.putExtra("eventTimeStamp", eventTimeStamp);
							intentDirectLog.putExtra("eventDisplayIDFlag", "" + CurrentPrintIndex);
							intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivity(intentDirectLog);
							finish();
							overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
							//printFirstRecord();
						}
    				}.start();
    				// for viberating and using media player
    				/*try {
    					Vibrator myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
    					myVib.vibrate(3000);

    				} catch (Exception e) {
    					// TODO: handle exception
    					e.printStackTrace();
    				}*/

    				// How many times alert need to be display
    				if (reminder_number == 0) {
    					reminder_number = 3;

    				}
    				// Reminder Delay
    				if (event_reminder_time == 0) {
    					event_reminder_time = 60;

    				}
    				// Display Reminder
    				if (wait_time == 0) {
    					// if 0 then default will be 5
    					wait_time = 45 * 1000;
    				}
    				eventTTS = 1;
    				eventContPlay = 1;
    				eventSoundGap = 1000;

    				if (eventSoundGap == 0) {
    					eventSoundGap = 5;
    				}
    				if (eventTTS == 1 && eventContPlay == 1) {
    					AlertMessageSinglePreviewTesting.counter++;
    					soundManager = new SoundManager();
    					executor.scheduleAtFixedRate(soundManager, 0, 3000,
    							TimeUnit.MILLISECONDS);

    				}
    			}
    			catch(Exception e){
    				Log.v("Print Exception ","4 :" + e);
    			}
            }
		}
		catch(Exception e){
			Log.v("Print Exception ","5 :" + e);
		}
		
		/*soundManager = new SoundManager();
		executor.scheduleAtFixedRate(soundManager, 0, 3000, TimeUnit.MILLISECONDS);*/
	}




	//======================================================================
	
	public class ActivitySwipeDetector implements View.OnTouchListener {

		static final String logTag = "ActivitySwipeDetector";
		@SuppressWarnings("unused")
		private Activity activity;
		static final int MIN_DISTANCE = 100;
		private float downX, downY, upX, upY;

		public ActivitySwipeDetector(Activity activity){
		    this.activity = activity;
		}

		public void onRightToLeftSwipe(){
		    if(CurrentPrintIndex <= TotalEvents){
		    	 CurrentPrintIndex = CurrentPrintIndex + 1;
		    	 Log.v("CurrentPrintIndex ", " RightToLeftSwipe : " + CurrentPrintIndex);
		    	 	executor.shutdown();
					executor.shutdownNow();
					executor.remove(soundManager);

					/*executor1.shutdown();
					executor1.shutdownNow();
					executor1.remove(soundManager1);*/
					if (talker != null) {
						talker.stop();
						talker.shutdown();
					}
					

		    	 //printFirstRecord();
					Intent intentDirectLog = new Intent(getBaseContext(),
							AlertMessageSinglePreview.class);
					intentDirectLog.putExtra("eventTimeStamp", eventTimeStamp);
					intentDirectLog.putExtra("eventDisplayIDFlag", "" + CurrentPrintIndex);
					intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intentDirectLog);
					finish();
					overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		    }
		    
		    //activity.doSomething();
		}

		public void onLeftToRightSwipe(){
		    if(CurrentPrintIndex > 0){
		    	CurrentPrintIndex = CurrentPrintIndex - 1;
		    	 Log.v("CurrentPrintIndex ", " LeftToRightSwipe : " + CurrentPrintIndex);
		    	 	executor.shutdown();
					executor.shutdownNow();
					executor.remove(soundManager);

					/*executor1.shutdown();
					executor1.shutdownNow();
					executor1.remove(soundManager1);*/
					if (talker != null) {
						talker.stop();
						talker.shutdown();
					}
					

		    	//printFirstRecord();
					Intent intentDirectLog = new Intent(getBaseContext(),
							AlertMessageSinglePreview.class);
					intentDirectLog.putExtra("eventTimeStamp", eventTimeStamp);
					intentDirectLog.putExtra("eventDisplayIDFlag", "" + CurrentPrintIndex);
					intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intentDirectLog);
					finish();
					overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		    }
		    
		   // activity.doSomething();
		}

		public void onTopToBottomSwipe(){
		    if(TotalEvents > 1){
	    		executor.shutdown();
				executor.shutdownNow();
				executor.remove(soundManager);

				/*executor1.shutdown();
				executor1.shutdownNow();
				executor1.remove(soundManager1);*/
				if (talker != null) {
					talker.stop();
					talker.shutdown();
				}
				
		    	checkMultipleActive = true;
		    	Log.v("Print ", "onTopToBottomSwipe : " + checkMultipleActive);
		    	eventsMainArray = "";
		    	eventsListObjArray = new JSONObject();
		    	eventsListArray.clear();
		    	updateState();
				//setNextReminder();
	    		
		    }
		    else{
		    	updateState();
		    }
		    //activity.doSomething();
		}

		public void onBottomToTopSwipe(){
		   // activity.doSomething();
		    if(TotalEvents > 1){
	    		executor.shutdown();
				executor.shutdownNow();
				executor.remove(soundManager);

				/*executor1.shutdown();
				executor1.shutdownNow();
				executor1.remove(soundManager1);*/
				if (talker != null) {
					talker.stop();
					talker.shutdown();
				}
			
		    	checkMultipleActive = true;
		    	Log.v("Print ", "onBottomToTopSwipe : " + checkMultipleActive);
		    	eventsMainArray = "";
		    	eventsListObjArray = new JSONObject();
		    	eventsListArray.clear();
		    	updateState();
				//setNextReminder();
	    		
		    }
		    else{
		    	updateState();
		    }
		}

		public boolean onTouch(View v, MotionEvent event) {
		    switch(event.getAction()){
		        case MotionEvent.ACTION_DOWN: {
		            downX = event.getX();
		            downY = event.getY();
		            return true;
		        }
		        case MotionEvent.ACTION_UP: {
		            upX = event.getX();
		            upY = event.getY();

		            float deltaX = downX - upX;
		            float deltaY = downY - upY;

		       // swipe horizontal?
		        if(Math.abs(deltaX) > Math.abs(deltaY))
		        {
		            if(Math.abs(deltaX) > MIN_DISTANCE){
		                // left or right
		                if(deltaX < 0) { this.onLeftToRightSwipe(); return true; }
		                if(deltaX > 0) { this.onRightToLeftSwipe(); return true; }
		            }
		            else {
		                    Log.i(logTag, "Horizontal Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
		                    return false; // We don't consume the event
		            }
		        }
		        // swipe vertical?
		        else 
		        {
		            if(Math.abs(deltaY) > MIN_DISTANCE){
		                // top or down
		                if(deltaY < 0) { this.onTopToBottomSwipe(); return true; }
		                if(deltaY > 0) { this.onBottomToTopSwipe(); return true; }
		            }
		            else {
		                    Log.i(logTag, "Vertical Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
		                    return false; // We don't consume the event
		            }
		        }

		            return true;
		        }
		    }
		    return false;
		}

		@SuppressWarnings("unused")
		private void onUpSwipe() {
			// TODO Auto-generated method stub
			
		}

		@SuppressWarnings("unused")
		private void onDownSwipe() {
			// TODO Auto-generated method stub
			
		}
		}
	
	public void onRightSwipe(View v){
       // Log.i(logTag, "RightToLeftSwipe!");
    }
	
	public void closeExcecutor() {
		// TODO Auto-generated method stub
		executor.shutdown();
		executor.shutdownNow();
		executor.remove(soundManager);

		/*executor1.shutdown();
		executor1.shutdownNow();
		executor1.remove(soundManager1);*/
		
		// Don't forget to shutdown!
		if (talker != null) {
			talker.stop();
			talker.shutdown();
		}
		
	}




	public void onLeftSwipe(View v){
	       // Log.i(logTag, "LeftToRightSwipe!");
	}
		
    
    class SoundManager implements Runnable {

		int counter = 0;

		@Override
		public void run() {

			if ((counter % 2) == 0) {

				setVolumeControlStream(AudioManager.STREAM_MUSIC);
				// our file here is in fact called "soundfile.mp3";

				player = MediaPlayer.create(
						AlertMessageSinglePreviewTesting.this, R.raw.alarm);
				// we start playing the file!
				player.start();

				player.setOnCompletionListener(new OnCompletionListener() {

					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.stop();
						mp.release();
					}
				});

			} else if ((counter % 2) != 0) {
				String text = evtDes;
				talker.speak(text, TextToSpeech.QUEUE_FLUSH, null);
			}
			counter++;
		}

	}

	class SoundManager1 implements Runnable {

		@Override
		public void run() {

			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			// our file here is in fact called "soundfile.mp3";

			player = MediaPlayer.create(AlertMessageSinglePreviewTesting.this,
					R.raw.alarm);
			// we start playing the file!
			player.start();

			player.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					mp.stop();
					mp.release();
				}
			});
		}

	}

	// ==========================================================
	private String getAddDateTimeStringPreCheck() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}
	
	// ===========================================================
	public long getNativeTimeStamp(String DateSend, String Time, String Tzone) {
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm zzzzz");
		Calendar c = Calendar.getInstance();
		Date d = null;
		try {
			d = ddMMMyyFormat.parse(DateSend.trim() + " " + Time.trim() + Tzone);
		} catch (ParseException e) {
			Log.v("Print Exception ","6 :" + e);
		}

		c.setTime(d);

		@SuppressWarnings("unused")
		String date_to_string = ddMMMyyFormat.format(c.getTimeInMillis() / 1000);
		TimeStampValue = c.getTimeInMillis() / 1000;
		return c.getTimeInMillis() / 1000;
	}
	
	// ==========================================================	
		protected void eventDetailsUpdate() {
			Log.v(">>>>>>>>>>>>>>>>> ","Event Details Update");
			// TODO Auto-generated method stub
			String UpdatedEvent = etEventMainId.getText().toString();
			Log.v("Print ", "updateEventId : " + UpdatedEvent);
			mydb = openOrCreateDatabase(DATABASE_NAME,
					Context.MODE_PRIVATE, null);
			Cursor checkPreEventsAckCount = null;

			try {
				String query = "SELECT event_log_id,event_time_stamp,event_alam_time,event_ack_count,eventReminderTime,eventReminderNumber,eventWaitTime,eventTimeStamp FROM table_events Where event_log_id = '" + UpdatedEvent + "'";
				checkPreEventsAckCount = mydb.rawQuery(query, null);
			} catch (Exception e) {
				Log.v("Print Exception ","7 :" + e);
			}
			if (checkPreEventsAckCount != null) {
				if (checkPreEventsAckCount.getCount() > 0) {
					while (checkPreEventsAckCount.moveToNext()) {
						ContentValues updateEvetsCount = new ContentValues();
						String updateID = checkPreEventsAckCount.getString(0);
						String event_alam_time = checkPreEventsAckCount.getString(2);
						long event_alam_timecount = Long.parseLong(event_alam_time);
						String updateCounter = checkPreEventsAckCount.getString(3);
						String eventReminderTime = checkPreEventsAckCount.getString(4);
						String eventReminderNumber = checkPreEventsAckCount.getString(5);
						String eventWaitTime = checkPreEventsAckCount.getString(6);
						String eventCurrentTimeStamp = checkPreEventsAckCount.getString(7);

						int eventReminderNumbercount = Integer.parseInt(eventReminderNumber);
						// Event Reminder Time = Time 1
						long eventReminderTimecount = Long.parseLong(eventReminderTime);
						long eventeventWaitTimecount = Long.parseLong(eventWaitTime);
						long eventeventCurrentTimeStamp = Long.parseLong(eventCurrentTimeStamp);

						Log.v("","Reminder Time Count****: " + eventReminderTimecount);
						Log.v("","Wait Time Count********: " + eventeventWaitTimecount);
						
						long curCount = Long.parseLong(updateCounter);
						curCount = curCount + 1;

						long newEventCurrentTimeStamp = (eventReminderTimecount + eventeventWaitTimecount) * curCount;
						newEventCurrentTimeStamp = newEventCurrentTimeStamp + TimeStampValue;
						String newEventCurrentTimeStampStr = String.valueOf(newEventCurrentTimeStamp);
						
						Log.v("","Current Time Stamp*****: " + newEventCurrentTimeStampStr);

						if (eventReminderNumbercount == curCount) {
							updateEvetsCount.put("event_status", "4");
							updateEvetsCount.put("event_ack_count", curCount);
							updateEvetsCount.put("event_active", "1");
							updateEvetsCount.put("event_alam_time", newEventCurrentTimeStampStr);
							mydb.update(MEM_EVENT, updateEvetsCount, "event_log_id ='" + updateID + "'", null);
						} else {
							nextReminderTimeStamp = newEventCurrentTimeStamp;
							newEventCurrentTimeStampStr = String.valueOf(nextReminderTimeStamp);
							updateEvetsCount.put("event_ack_count", curCount);
							updateEvetsCount.put("event_status", "9");
							updateEvetsCount.put("event_alam_time", newEventCurrentTimeStampStr);
							mydb.update(MEM_EVENT, updateEvetsCount, "event_log_id ='" + updateID + "'", null);
						}

					}
				}
			}
			checkPreEventsAckCount.close();
			mydb.close();
			//printFirstRecord();  
			CurrentPrintIndex = 0;
		}
		
		// ===========================================================

		protected void setNextReminder() {
			try{
				Bundle bundle = new Bundle();
				EventAlarm alarm1 = new EventAlarm(getBaseContext(), bundle, event_reminder_time);
			}
			catch(Exception e){
				Log.v("Print Exception ","8 :" + e);
			}
			
		}

		// ===========================================================
		
		@Override
		public void onDestroy() {
			super.onDestroy();
			executor.shutdown();
			executor.shutdownNow();
			executor.remove(soundManager);

			/*executor1.shutdown();
			executor1.shutdownNow();
			executor1.remove(soundManager1);*/
			// Don't forget to shutdown!
			if (talker != null) {
				talker.stop();
				talker.shutdown();
			}
		}

		@Override
		protected void onStop() {
			super.onStop();
			executor.shutdown();
			executor.shutdownNow();
			executor.remove(soundManager);

			/*executor1.shutdown();
			executor1.shutdownNow();
			executor1.remove(soundManager1);*/
			// Don't forget to shutdown!
			if (talker != null) {
				talker.stop();
				talker.shutdown();
			}
		};



		@Override
		public void onInit(int arg0) {
			// TODO Auto-generated method stub
			
		}
		
		
		
		//*******************Update Acknoledge States******************

		protected void updateState() {
			// TODO Auto-generated method stub
			String UpdatedEvent = etEventMainId.getText().toString();
			Log.v("Print ", "updateEventId : " + UpdatedEvent);
			mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
			Cursor checkPreEvents = null;
			try {
				String query = "SELECT event_log_id,event_time_stamp,event_alam_time,event_url,event_package FROM table_events Where event_log_id = '" + UpdatedEvent + "'";
				checkPreEvents = mydb.rawQuery(query, null);
			} catch (Exception e) {
				Log.v("Print Exception ","9 :" + e);
			}
			if (checkPreEvents != null) {
				if (checkPreEvents.getCount() > 0) {
					while (checkPreEvents.moveToNext()) {
						Log.v("******@@@@@@@","******");
						ContentValues updateEvets = new ContentValues();
						String updateID = checkPreEvents.getString(0);
						eventURL = checkPreEvents.getString(3);
						eventPackage = checkPreEvents.getString(4);

						updateEvets.put("event_status", "3");
						updateEvets.put("event_active", "1");
						updateEvets.put("event_update_time", getAddDateTimeString().toString());
						mydb.update(MEM_EVENT, updateEvets, "event_log_id ='" + UpdatedEvent + "'", null);
					}
				}
			}
			checkPreEvents.close();
			mydb.close();
			
			Log.e("REQUEST 1:", "VAL PASS 1 :" +eventURL);
			Log.e("REQUEST 2:", "VAL PASS 2 :" +eventPackage);
			
			if (eventPackage.equals("404") && eventURL.equals("404")) {
				//closeExcecutor();
				/*AlertMessageSinglePreviewM.this.finish();
				finish();
				android.os.Process.killProcess(android.os.Process.myPid());*/
				if(checkMultipleActive = true){
					if(TotalEvents > 1){
						CurrentPrintIndex = 0;
						reloadEvents();
					}
					else{
						//closeExcecutor();
						AlertMessageSinglePreviewTesting.this.finish();
						finish();
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				}
			} else if (!eventURL.equals("404")) {
				try {
					Log.e("REQUEST :", "Fire URL**********");
					//closeExcecutor();
					Intent viewIntent = new Intent("android.intent.action.VIEW",
							Uri.parse(eventURL.trim()));
					viewIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
	                         | Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(viewIntent);
					AlertMessageSinglePreviewTesting.this.finish();
					finish();
					android.os.Process.killProcess(android.os.Process.myPid());
				} catch (Exception e) {
					Log.v("Print Exception ","10 :" + e);
				}
			} else if (!eventPackage.equals("404")) {
				Log.e("REQUEST :", "Fire Package************");
				//closeExcecutor();
				Intent i = new Intent(Intent.ACTION_MAIN);
				i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
	                    | Intent.FLAG_ACTIVITY_NEW_TASK);
				PackageManager managerclock = getPackageManager();
				i = managerclock.getLaunchIntentForPackage(eventPackage.trim());
				i.addCategory(Intent.CATEGORY_LAUNCHER);
				startActivity(i);
				AlertMessageSinglePreviewTesting.this.finish();
				finish();
				android.os.Process.killProcess(android.os.Process.myPid());
			}
			else{
				if(checkMultipleActive = true){
					if(TotalEvents > 1){
						CurrentPrintIndex = 0;
						reloadEvents();
					}
					else{
						closeExcecutor();
						AlertMessageSinglePreviewTesting.this.finish();
						finish();
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				}
			}
			/*
			 * //Allow To Trigger If Previous Events Excisting Bundle bundle = new
			 * Bundle(); EventAlarm alarm1 = new EventAlarm(this, bundle, 1);
			 */
		}
		
		private void reloadEvents() {
			// TODO Auto-generated method stub
			Intent intentDirectLog = new Intent(getBaseContext(),
					AlertMessageSinglePreview.class);
			intentDirectLog.putExtra("eventTimeStamp", eventTimeStamp);
			intentDirectLog.putExtra("eventDisplayIDFlag", "" + CurrentPrintIndex);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intentDirectLog);
			finish();
			overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
			
			/*mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
			ContentValues newrowfDealer = new ContentValues();
			Cursor fdealerrows = null;
			try {
				String query = "SELECT * FROM table_events WHERE eventTimeStamp = '" + eventTimeStamp + "' AND event_active = '0'";
				fdealerrows = mydb.rawQuery(query, null);
			} catch (Exception e) {
				Log.v("Print Exception ","11 :" + e);
			}
			if (fdealerrows != null) {
				if (fdealerrows.getCount() > 0) {
					Log.v("Total Count "," : " + fdealerrows.getCount());
					TotalEvents = fdealerrows.getCount();
					int eventIndexCounter = 0;
					while (fdealerrows.moveToNext()) {
						
						Log.v("@@@@@@@@@@@@ "," : " + eventIndexCounter);
						JSONObject eventsListObj = new JSONObject();
						try{
							eventsListObj.put("event_rf_id", eventIndexCounter);
							eventsListObj.put("title", fdealerrows.getString(3));
							eventsListObj.put("description", fdealerrows.getString(4));
							eventsListObj.put("reminder_date", fdealerrows.getString(6));
							eventsListObj.put("reminder_time", fdealerrows.getString(7));
							
							int  eventPrintCount = eventIndexCounter;
							eventPrintCount =  eventPrintCount + 1;
							eventsListObj.put("event_count_flag", eventPrintCount + "  Of  " + TotalEvents + "  Events");
							
							eventsListObj.put("event_id", fdealerrows.getString(1));
							eventsListObj.put("event_alam_time", fdealerrows.getString(8));
							eventsListObj.put("event_url", fdealerrows.getString(11));
							eventsListObj.put("event_package", fdealerrows.getString(12));
							eventsListObj.put("event_ack_count", fdealerrows.getString(15));
							eventsListObj.put("eventReminderTime", fdealerrows.getString(16));
							eventsListObj.put("eventReminderNumber", fdealerrows.getString(17));
							eventsListObj.put("eventWaitTime", fdealerrows.getString(18));
							eventsListObj.put("eventNotifyType", fdealerrows.getString(19));
							eventsListArray.add(eventsListObj.toString());
							eventIndexCounter = eventIndexCounter + 1;
						}
						catch(Exception e){
							Log.v("Print Exception ","12 :" + e);
						}
						
					}
					
					try{
						eventsListObjArray = new JSONObject();
						String EventsArray = eventsListArray.toString();
						eventsListObjArray.put("events", EventsArray);
						
					}
					catch(Exception e){
						Log.v("Print Exception ","13 :" + e);
					}
					//displayEvent();
					printFirstRecord();
				}
			}*/
		}

		private String getAddDateTimeString() {
			Calendar cad = Calendar.getInstance();
			SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String formattedAddDate = dfad.format(cad.getTime());
			return formattedAddDate;
		}
}
